<template>
  <div class="shujia">
    <div class="search-box">
      <h2>书架</h2>
      <van-search class="search" left-icon shape="round" right-icon="search" v-model="value" placeholder="快速查找收藏漫画"
        @click-right-icon="findComics" @input="showCollectComics" />
      <span @click="edit">{{ isEdit ? '完成' : '编辑' }}</span>
    </div>
    <div class="bookList">
      <div class="book-left">
        <span :class="{ active: itemIndex === index }" v-for="(item, index) in bookList" :key="index"
          @click="toggleContent(index)">{{ item.name }}</span>
      </div>
      <div class="book-right">
        <span>
          <van-icon name="plus" @click="showbottomSidebar" />添加漫画
          <van-popup v-model="show" position="bottom" :style="{ height: '36%' }" closeable>
            <h3>热门漫画推荐</h3>
            <div class="replay">
              <span @click="changeTheNovel">
                <van-icon name="replay" />换一换
              </span>
            </div>
            <div class="comic-box">
              <div class="comic-item" v-for="(item, index) in shujiaFictionData" :key="index">
                <img v-lazy="item.vertical_cover" />
                <p>
                  <b>{{ item.title }}</b>
                  <van-icon name="like" @click="pursueComic(index, item.comic_id)"
                    :color="comicIndex === index ? '#ff3f3f' : '#333'" />
                </p>
              </div>
            </div>
          </van-popup>
        </span>
      </div>
    </div>
    <div class="zhuiman">
      <div class="collect-books" v-if="ComicData.length === 0 && isLogin == 1">
        <div class="err">
          <van-empty description="暂未收藏漫画!" />
        </div>
      </div>
      <div class="collect-books" v-if="ComicData.length > 0 && isLogin == 1">
        <div class="item-book" v-for="(item, index) in ComicData" :key="index">
          <img @click="readComic(item.id, item.title)" v-lazy="item.vertical_cover" />
          <h3 class="title">{{ item.title }}</h3>
          <span>{{ item.read_epid + 1 }}话/{{ item.total }}话</span>
          <span :class="[isEdit ? 'delete' : 'del']" @click="deleteComic(index)">X</span>
        </div>
      </div>
      <div v-if="isLogin == 0" class="p-login"><button @click="goLogin">请登录</button></div>
    </div>
  </div>
</template>

<script>
import { bookList } from "@/js/data";
import { getcomicDetail, getClassPageSixComics } from "@/api/api";
export default {
  name: "Shujia",
  data() {
    return {
      //书架
      value: "",
      active: 0,
      bookList,
      itemIndex: 0,
      ids: [],
      show: false,
      shujiaFictionData: [],
      comicIndex: -1,
      //是否编辑
      isEdit: false,
      comicChapterIndex: 0,
      //追漫
      ComicData: [],
      typeIds: [],
      //章节id
      comicId: "",
      //是否登录
      isLogin: 0,
    };
  },
  created() {
    //判断是否登录,已登录即可收藏成功,否者需要登录在收藏
    //获取收藏的漫画
    this.ids = JSON.parse(localStorage.getItem("ids"));
    this.getId(this.ids, this.ComicData);
    //获取已看漫画章节数
    // let res=localStorage.getItem("continueTheChapter");
    // if(res){
    //   JSON.parse(res).map((item,i)=>{
    //   // this.ComicData[i].read_epid=Number(item.index)
    // })
    // }else{
    //   res=[]
    // }
    //获取本地存储的该漫画对应章节
    // let continueTheChapter = JSON.parse(
    //   localStorage.getItem("continueTheChapter")
    // );
    // if (continueTheChapter) {
    //   for (let i = 0; i < continueTheChapter.length; i++) {
    //     if (this.ids.includes(continueTheChapter[i].comicId)) {
    //      console.log(continueTheChapter[i].index);
    //     }
    //   }
    // }
  },
  activated() {
    this.isLogin = localStorage.getItem("isLogin");
  },
  computed: {
    // getIslogin() {
    //   console.log(this.$store.state.isLogin)
    //   return this.$store.state.isLogin
    // }
  },
  methods: {
    //切换选项
    toggleContent(index) {
      if (this.itemIndex === index) {
        return;
      }
      this.itemIndex = index;
    },
    //编辑
    edit() {
      if (this.isLogin == 0) this.goLogin()
      else this.isEdit = !this.isEdit;
    },
    //查找收藏对应名的漫画
    findComics() {
      if (this.value.length === 0 || this.isLogin == 0) {
        return;
      }
      this.typeIds = []
      this.ComicData.forEach(item => {
        if (item.title.indexOf(this.value) === 0) {
          this.typeIds.push(item.id);
          //显示输入名字对应的漫画
          this.ComicData = [];
          this.getId(this.typeIds, this.ComicData);
        }
      });
    },
    showCollectComics() {
      console.log(333)
      if (this.value.length === 0) {
        this.typeIds = [];
        //恢复默认的全部收藏漫画
        this.ComicData = [];
        this.getId(this.ids, this.ComicData);
      }
    },
    //显示下边栏
    showbottomSidebar() {
      this.show = true;
      this.changeTheNovel();
      this.comicIndex = -1;
    },
    //换一换
    changeTheNovel() {
      let num = Math.floor(Math.random() * 51);
      this.getRecommendComic(num);
    },
    //获取推荐的漫画小说
    getRecommendComic(num) {
      getClassPageSixComics(num, 3)
        .then(res => {
          this.shujiaFictionData = [];
          if (res.data.code === 0) {
            if (this.ids) {
              res.data.data.roll_six_comics.filter(item => {
                for (let i = 0; i < this.ids.length; i++) {
                  if (item.comic_id == this.ids[i]) {
                    return;
                  }
                }
                this.shujiaFictionData.push(item);
              });
            } else {
              this.shujiaFictionData = res.data.data.roll_six_comics;
            }
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    //追漫
    pursueComic(index, id) {
      this.isLogin = localStorage.getItem("isLogin");
      //判断是否登录,已登录即可收藏成功,否者需要登录在收藏
      if (this.isLogin == 1) {
        this.comicIndex = index;
        this.show = false;
        // if (this.ids) {
        //   this.ids;
        // } else {
        //   this.ids = [];
        // }
        this.ids.unshift(id);
        localStorage.setItem("ids", JSON.stringify(this.ids));
        //重新加载追漫区内容
        this.ComicData = [];
        this.getId(this.ids, this.ComicData);
      } else {
        let path = this.$route.fullPath;
        localStorage.setItem("path", JSON.stringify(path));
        this.$router.push("/login");
      }
    },
    //删除对应书籍
    deleteComic(id) {
      this.ids.splice(id, 1);
      localStorage.setItem("ids", JSON.stringify(this.ids));
      //删除书籍移出书库收藏
      this.ComicData.splice(id, 1)
      if (this.ComicData.length == 0) this.isEdit = false
    },
    //通过漫画id获取漫画详情
    getId(id, data) {
      if (id) {
        for (let i = 0; i < id.length; i++) {
          if (id[i] == "") {
            return;
          }
          getcomicDetail(id[i])
            .then(res => {
              data.push(res.data.data);
            })
            .catch(err => {
              console.log(err);
            });
        }
      }
    },
    //阅读漫画
    readComic(comicId, title) {
      getcomicDetail(comicId)
        .then(res => {
          this.allList = res.data.data.ep_list.reverse();
          //获取本地存储的该漫画对应章节
          let continueTheChapter = JSON.parse(
            localStorage.getItem("continueTheChapter")
          );
          if (continueTheChapter) {
            for (let i = 0; i < continueTheChapter.length; i++) {
              if (continueTheChapter[i].comicId == comicId) {
                this.comicId = continueTheChapter[i].chapter;
                this.comicChapterIndex = continueTheChapter[i].index - 1;
                break;
              } else {
                this.comicId = this.allList[0].id;
              }
            }
          } else {
            this.comicId = this.allList[0].id;
          }
          //本地存储每个漫画章节列表
          localStorage.setItem("allList", JSON.stringify(this.allList));
          let path = "/seecomic";
          let fullPath = this.$route.fullPath;
          this.$router.push({
            path,
            query: {
              comicId,
              comicChapterId: this.comicId,
              path: fullPath,
              title,
              index: Number(this.comicChapterIndex) + 1
            }
          });
        })
        .catch(err => {
          console.log(err);
        });
    },
    //进入登录进行登录
    goLogin() {
      let path = this.$route.fullPath;
      localStorage.setItem("path", JSON.stringify(path));
      this.$router.push("/login")
    }
  }
};
</script>

<style lang="scss" scoped>
.shujia {
  .search-box {
    display: flex;
    align-items: center;
    justify-content: space-around;

    .search {
      width: 260px;
    }

    span {
      font-size: 14px;
    }

    ::v-deep .van-tab {
      display: 50px;
    }
  }

  .bookList {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;
    margin-top: 5px;

    ::v-deep .van-popup__close-icon--top-right {
      top: 5px;
      right: 5px;
    }

    .book-left {
      span {
        font-size: 14px;
        margin-right: 10px;
        color: #777;
        position: relative;

        &:last-child {
          margin-right: 0;
        }

        &.active {
          color: #5c55ff;
          font-size: 16px;
          font-weight: bold;
        }
      }
    }

    .book-right {
      span {
        display: inline-block;
        height: 30px;
        line-height: 30px;
        border: 1px solid #333;
        border-radius: 30px;
        padding: 0 10px;
      }

      font-size: 14px;

      h3 {
        text-align: center;
        font-size: 18px;
        margin-top: 5px;
        margin-bottom: 5px;
      }

      .replay {
        display: flex;
        justify-content: end;
        padding: 0 10px;
        margin-bottom: 5px;
      }

      .comic-box {
        padding: 0 10px;
        display: flex;

        .comic-item {
          width: 33%;
          text-align: center;

          img {
            width: 100px;
            vertical-align: bottom;
          }

          p {
            margin: 0;
            font-size: 16px;
            display: flex;
            align-items: center;
            justify-content: center;

            b {
              display: inline-block;
              width: 90px;
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
            }
          }
        }
      }
    }
  }

  .zhuiman {
    padding: 10px;
    padding-bottom: 50px;

    .collect-books {
      display: flex;
      flex-wrap: wrap;

      .err {
        flex: 1;
      }

      .item-book {
        width: 110px;
        margin-right: 10px;
        position: relative;
        margin-bottom: 10px;

        &:nth-child(3n) {
          margin-right: 0;
        }

        img {
          width: 100%;
          border-radius: 4px;
          border: 1px solid #f1f1f1;
        }

        .title {
          margin: 0;
          font-size: 16px;
          text-overflow: ellipsis;
          white-space: nowrap;
          overflow: hidden;
        }

        span {
          font-size: 14px;
        }

        .delete {
          position: absolute;
          top: 0;
          right: -2px;
          display: inline-block;
          width: 25px;
          height: 25px;
          text-align: center;
          line-height: 25px;
          background: #fff;
          font-weight: bold;
          border-bottom-left-radius: 20px;
          display: block;
          z-index: 999;
        }

        .del {
          display: none;
        }
      }
    }

    .p-login {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);

      button {
        width: 100px;
        height: 40px;
        border: none;
        color: #5c55ff;
        border-radius: 4px;
        font-weight: bold;
      }
    }
  }
}
</style>